import { Col } from "./data_ext";

export class Audio {
    private __domCol: Col<HTMLAudioElement> = {};
    private static __ins: Audio = null;

    getDom(key: string) {
        if (this.__domCol[key]) {
            return this.__domCol[key];
        }
        let dom = document.createElement("audio");
        dom.style.display = "none";
        document.body.appendChild(dom);
        this.__domCol[key] = dom;
        return dom;
    }
    static get ins() {
        if (!Audio.__ins) {
            Audio.__ins = new Audio();
        }
        return Audio.__ins;
    }

    volume = 1; //0-1
    play(path: string, isLoop = false) {
        let dom = this.getDom(path);
        dom.src = path;
        dom.volume = this.volume;
        dom.loop = isLoop;
        dom.oncanplay = () => {
            dom.play();
        }
        //@ts-ignore
        return new Promise<void>(ok => dom.onended = ok);
    }
    pause(path: string) {
        let dom = this.getDom(path);
        if (dom) {
            dom.pause();
        }
    }
};